import {Alert, Divider, Flex, Tag, Typography} from "antd";
import {Bubble} from "@ant-design/x";
import {AiSender} from "./AiSender.tsx";
import {useEffect, useRef, useState} from "react";
import {FileOutlined} from "@ant-design/icons";
import {useTheme} from "../../context/ThemeContext.tsx";
import * as chatController from "../../api/chatController";
import 藏獒Img from "../../assets/藏獒.svg";
import 荷兰猪Img from "../../assets/荷兰猪.svg";

interface AiMessageContentProps {
    conversationId: string;
    uploadedFiles?: string[];
}

export const AIMessageContent = (props: AiMessageContentProps) => {
    const [conversation, setConversation] = useState<API.ConversationVO>({messages: []});
    const {theme: currentTheme} = useTheme();
    const isInk = currentTheme === 'ink';
    const {uploadedFiles = []} = props;

    const scrollRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (props.conversationId) {
            chatController.get({conversationId: props.conversationId}).then((response) => {
                if (response.data && response.data.code === 0 && response.data.data) {
                    setConversation(response.data.data);
                }
            });
        }
    }, [props.conversationId]);

    useEffect(() => {
        if (scrollRef.current) {
            scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
    }, [conversation]);

    // 对话为空时显示欢迎消息
    const showWelcomeMessage = !conversation.messages || conversation.messages.length === 0;

    return (
        <Flex
            vertical
            style={{
                height: "100%",
                width: "100%",
                position: "relative",
            }}
        >
            <Flex
                ref={scrollRef}
                vertical
                gap={16}
                style={{
                    height: "calc(100% - 80px)",
                    overflowY: "auto",
                    padding: "20px 30px",
                    marginBottom: "80px",
                    background: "rgba(255, 255, 255, 0.7)",
                    borderRadius: "8px",
                    backgroundImage: `var(--pattern)`,
                }}
            >
                {showWelcomeMessage ? (
                    <div style={{
                        textAlign: 'left',
                        padding: '20px',
                        background: isInk ? 'rgba(230, 244, 255, 0.6)' : 'rgba(255, 241, 240, 0.6)',
                        borderRadius: isInk ? '8px' : '16px',
                        marginTop: '20px',
                        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.05)',
                        border: isInk ? '1px solid #bae0ff' : '1px solid #ffccc7'
                    }}>
                        <Flex align="center" gap={12}>
                            <div style={{
                                width: '30px',
                                height: '30px',
                                borderRadius: '50%',
                                overflow: 'hidden'
                            }}>
                                <img 
                                    src={荷兰猪Img} 
                                    alt="AI头像" 
                                    style={{
                                        width: '100%',
                                        height: '100%',
                                        objectFit: 'cover'
                                    }}
                                />
                            </div>
                            <Typography.Title level={4} style={{
                                margin: 0,
                                color: isInk ? '#1677ff' : '#ff6b6b',
                                fontFamily: 'var(--font-family)'
                            }}>
                                AI知识库助手
                            </Typography.Title>
                        </Flex>
                        <Divider style={{margin: '12px 0'}}/>
                        <Typography.Paragraph style={{
                            marginBottom: 0,
                            fontFamily: 'var(--font-family)'
                        }}>
                            您好！我是您的AI知识库助手，可以帮您：
                            <ul style={{paddingLeft: '20px', marginTop: '8px'}}>
                                <li>回答您关于知识库中文档的问题</li>
                                <li>分析您上传的文件内容</li>
                                <li>提供相关知识的专业解答</li>
                            </ul>
                            请输入您的问题，开始我们的对话吧！
                        </Typography.Paragraph>
                    </div>
                ) : (
                    conversation.messages?.map((v, index) => {
                        const isLastMessage = index === conversation.messages!.length - 1;

                        return v.type === "USER" ? (
                            <Bubble
                                key={`msg-${index}`}
                                content={
                                    <Typography.Text strong style={{
                                        color: isInk ? "#1677ff" : "#ff6b6b",
                                        fontFamily: 'var(--font-family)',
                                        fontSize: '15px'
                                    }}>
                                        {v.content}
                                    </Typography.Text>
                                }
                                placement={"end"}
                                style={{
                                    maxWidth: "85%",
                                    background: isInk ? "#e6f4ff" : "#fff1f0",
                                    border: isInk ? "1px solid #bae0ff" : "1px solid #ffccc7",
                                    boxShadow: "0 2px 6px rgba(0, 0, 0, 0.05)",
                                    borderRadius: isInk ? "8px 2px 8px 8px" : "16px 4px 16px 16px",
                                    padding: "12px 16px",
                                    marginLeft: "auto",
                                }}
                                className="message-appear"
                                avatar={
                                    <div style={{
                                        borderRadius: '50%',
                                        width: '40px',
                                        height: '40px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        overflow: 'hidden',
                                        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
                                    }}>
                                        <img 
                                            src={藏獒Img} 
                                            alt="用户头像" 
                                            style={{
                                                width: '100%',
                                                height: '100%',
                                                objectFit: 'cover'
                                            }}
                                        />
                                    </div>
                                }
                            />
                        ) : (
                            <Bubble
                                key={`msg-${index}`}
                                content={<AssistantMsg content={v.content || ""}/>}
                                placement={"start"}
                                style={{
                                    maxWidth: "85%",
                                    background: "#ffffff",
                                    border: isInk ? "1px solid #f0f0f0" : "1px solid #ffe7ba",
                                    boxShadow: "0 2px 6px rgba(0, 0, 0, 0.05)",
                                    borderRadius: isInk ? "2px 8px 8px 8px" : "4px 16px 16px 16px",
                                    padding: "12px 16px",
                                    marginRight: "auto",
                                }}
                                className={isLastMessage && v.content && v.content.includes("思考中") ? "thinking-dots" : "assistant-message-appear"}
                                avatar={
                                    <div style={{
                                        borderRadius: '50%',
                                        width: '40px',
                                        height: '40px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        overflow: 'hidden',
                                        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
                                    }}>
                                        <img 
                                            src={荷兰猪Img} 
                                            alt="AI头像" 
                                            style={{
                                                width: '100%',
                                                height: '100%',
                                                objectFit: 'cover'
                                            }}
                                        />
                                    </div>
                                }
                            />
                        );
                    })
                )}

                {uploadedFiles.length > 0 && (
                    <Alert
                        message="已上传文件"
                        description={
                            <Flex vertical>
                                {uploadedFiles.map((file, index) => (
                                    <Flex key={index} align="center" gap="small">
                                        <FileOutlined/>
                                        <Typography.Text>{file}</Typography.Text>
                                    </Flex>
                                ))}
                            </Flex>
                        }
                        type="info"
                        showIcon
                        style={{
                            borderRadius: isInk ? "4px" : "12px",
                            fontFamily: 'var(--font-family)',
                            marginTop: '16px',
                            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.03)'
                        }}
                    />
                )}
            </Flex>
            <div
                style={{
                    position: "absolute",
                    bottom: 0,
                    left: 0,
                    right: 0,
                    padding: "16px 20px",
                    background: "#fff",
                    borderTop: `1px solid var(--border-color)`,
                    boxShadow: "0 -2px 8px rgba(0, 0, 0, 0.06)",
                    borderRadius: "0 0 8px 8px",
                    zIndex: 10,
                    backgroundImage: 'var(--card-bg)',
                }}
            >
                <AiSender
                    conversationId={props.conversationId}
                    setConversationId={() => {}}
                    setConversation={setConversation}
                    conversation={conversation}
                    uploadedFiles={uploadedFiles}
                    onFilesChange={() => {}}
                ></AiSender>
            </div>
        </Flex>
    );
};

interface AssistantMsgProps {
    content: string;
}

const AssistantMsg = (props: AssistantMsgProps) => {
    const {theme: currentTheme} = useTheme();
    const isInk = currentTheme === 'ink';

    const startTag = "<think>";
    const endTag = "</think>";

    const startIndex = props.content.indexOf(startTag);
    const endIndex = props.content.indexOf(endTag);

    let thinkContent = "";
    let outsideContent = "";

    if (startIndex !== -1 && endIndex !== -1) {
        thinkContent = props.content
            .substring(startIndex + startTag.length, endIndex)
            .trim();

        outsideContent = (
            props.content.substring(0, startIndex) +
            props.content.substring(endIndex + endTag.length)
        ).trim();
    } else {
        outsideContent = props.content;
    }

    return (
        <Flex vertical gap={12}>
            {thinkContent ? (
                <>
                    <Tag color={isInk ? "#87d068" : "#ffc53d"} style={{
                        fontWeight: 600,
                        borderRadius: isInk ? "4px" : "16px",
                        fontFamily: 'var(--font-family)',
                        padding: isInk ? "2px 8px" : "3px 12px",
                        display: 'inline-block',
                        marginBottom: '4px'
                    }} className="file-tag-appear">思考过程</Tag>
                    <Typography.Text type="secondary" style={{
                        whiteSpace: "pre-line",
                        fontSize: "14px",
                        lineHeight: isInk ? "1.8" : "1.6",
                        fontFamily: 'var(--font-family)',
                        display: 'block',
                        background: 'rgba(0, 0, 0, 0.02)',
                        padding: '10px',
                        borderRadius: '6px',
                        border: '1px solid rgba(0, 0, 0, 0.06)'
                    }}>
                        {thinkContent}
                    </Typography.Text>
                    <Divider style={{margin: '12px 0 8px'}}/>
                    <Tag color={isInk ? "#108ee9" : "#ff4d4f"} style={{
                        fontWeight: 600,
                        borderRadius: isInk ? "4px" : "16px",
                        fontFamily: 'var(--font-family)',
                        padding: isInk ? "2px 8px" : "3px 12px",
                        display: 'inline-block',
                        marginBottom: '4px'
                    }}>回答</Tag>
                    <Typography.Text style={{
                        whiteSpace: "pre-line",
                        fontSize: "14.5px",
                        lineHeight: isInk ? "1.8" : "1.6",
                        fontFamily: 'var(--font-family)',
                    }}>
                        {outsideContent}
                    </Typography.Text>
                </>
            ) : (
                <>
                    <Typography.Text style={{
                        whiteSpace: "pre-line",
                        fontSize: "14.5px",
                        lineHeight: isInk ? "1.8" : "1.6",
                        fontFamily: 'var(--font-family)',
                    }}>
                        {outsideContent}
                    </Typography.Text>
                </>
            )}
        </Flex>
    );
};
